/**
* @describe 公共工具
* @author 游金宇(KM)
* @date 2024-01-23 19:34:52
*/

import { error, ImageAsset, isValid, log, Sprite, SpriteFrame } from "cc";
import { cat } from '@shimotsuki/core';

/**重试函数 */
export const retryRequest = async (
    requestFunction: () => Promise<void>,
    maxRetries: number = 3,
    retryInterval: number = 1000 // milliseconds
) => {
    let retries = 0;

    const makeRequest = async () => {
        try {
            await requestFunction();
        } catch (err) {
            console.error(`Request failed. Retries left: ${maxRetries - retries}`);
            if (retries < maxRetries) {
                retries++;
                // Wait for the specified interval before retrying
                await new Promise(resolve => setTimeout(resolve, retryInterval));
                await makeRequest();
            } else {
                error(`Max retries reached. Unable to complete the request.`);
                throw (err)
            }
        }
    };

    await makeRequest();
};

/**加载图片 */
export const loadPhoto = (avatar: string, icon: Sprite, packable: boolean = false) => {

    if (avatar.indexOf("?") != -1) {
        avatar += "&time=" + new Date().getTime();
    }
    else {
        avatar += "?time=" + new Date().getTime();
    }
    log("avatar=", avatar);
    cat.res.loadRemote(avatar, (err: Error, imageAsset: ImageAsset) => {
        if (err) return error(err)
        if (isValid(icon)) {
            const spriteFrame = SpriteFrame.createWithImage(imageAsset)
            spriteFrame.packable = packable
            icon.spriteFrame = spriteFrame
        }
    })
}